<?php

namespace App\Services\Stock;

use App\CodeResponse;
use App\Enum;
use App\Models\Stock\StockTransfer;
use App\Repositories\Stock\StockTransferRepository;
use App\Services\BaseService;
use App\Services\Basic\StorageService;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class StockTransferService extends BaseService
{

    public function createTransfer($params)
    {
        $this->checkParams($params);
        //获取操作用户ID
        $params['user_id'] = get_user_id();

        //生成单号
        $params['transfer_no'] = $this->generateTransferNO();

        return app(StockTransferRepository::class)->create($params);
    }


    /**
     * 生成采购订单编号
     */
    public function generateTransferNo()
    {
        return retry(5, function () {
            $randomNumber = str_pad(random_int(1, 9999), 4, '0', STR_PAD_LEFT);
            $no = 'ZY' . date('YmdHis') . $randomNumber;
            if (!$this->isTransferNoUsed($no)) {
                return $no;
            }
            $this->throwBusinessException(CodeResponse::FAIL, '订单号获取失败');
        });
    }

    public function isTransferNoUsed($no)
    {
        return app(StockTransferRepository::class)->isExists(['transfer_no' => $no]);
    }


    public function updateTransfer($id, $params)
    {
        $this->checkParams($params);
        $this->updateCheck($id);
        //获取操作用户ID
        $params['user_id'] = get_user_id();

        return app(StockTransferRepository::class)->update($id, $params);
    }

    /**
     * @param $purchaseOrder
     * @return bool
     */
    public function isPending($data)
    {
        return $data->status == Enum::STOCK_TRANSFER_STATUS_PENDING ? true : false;
    }

    protected function checkParams($params)
    {
        if ($params['out_storage_id']===$params['in_storage_id']){
            return $this->throwBusinessException(CodeResponse::PARAM_ILLEGAL,'出入仓库不能相同');
        }

        if (!StorageService::getInstance()->isValid($params['out_storage_id'])){
            return $this->throwBusinessException(CodeResponse::PARAM_ILLEGAL,'出仓库ID错误');
        }

        if (!StorageService::getInstance()->isValid($params['in_storage_id'])){
            return $this->throwBusinessException(CodeResponse::PARAM_ILLEGAL,'入仓库ID错误');
        }

    }


    public function cancelTransfer($id)
    {
        $this->updateCheck($id);
        return app(StockTransferRepository::class)->update($id, ['status' => Enum::STOCK_TRANSFER_STATUS_CANCEL]);

    }

    public function updateCheck($id)
    {
        $stockTransfer = app(StockTransferRepository::class)->getById($id);
        if (!$stockTransfer) {
            $this->throwBusinessException(CodeResponse::FAIL, '获取转移单失败,id错误');
        }
        if (!$this->isPending($stockTransfer)) {
            $this->throwBusinessException(CodeResponse::FAIL, '订单不是待审核状态，不能进行修改');
        }
    }


    public function saveTotalCostPrice($id)
    {
        //获取所有条目的total_price
        $stockTransfer = StockTransfer::lockForUpdate()->find($id);
        if (!$this->isPending($stockTransfer)) {
            $this->throwBusinessException(CodeResponse::FAIL, '此订单已非待审状态，不支持操作');

        }
        $totalCostPrice = $stockTransfer->stockTransferItems()->sum('total_price');
        return StockTransfer::where('id', $id)->update(['total_cost_price' => $totalCostPrice]);

    }

    /**
     * 申请审核
     * @param $id
     * @return bool
     * @throws \App\Exceptions\BusinessException
     */
    public function review($id)
    {
        //开启事务
        DB::beginTransaction();
        try {
            $stockTransfer = StockTransfer::lockForUpdate()->find($id);
            if (!$this->isPending($stockTransfer)) {
                $this->throwBusinessException(CodeResponse::FAIL, '此订单已非待审状态，不支持操作');
            }
            //产品库存记录处理
            $stockTransferItems = $stockTransfer->stockTransferItems()->get();
            ProductStockService::getInstance()
                ->initData($stockTransferItems,$stockTransfer['out_storage_id'],$stockTransfer['in_storage_id'])
                ->handleTransfer();

            //修改采购订单状态
            StockTransfer::where('id', $id)->update([
                'status' => Enum::STOCK_TRANSFER_STATUS_APPROVED,
                'review_at' => date('Y-m-d H:i:s'),
                'finished_at' => date('Y-m-d H:i:s'),
                'review_user_id' => get_user_id()
            ]);

            DB::commit();
            return true;
        } catch (QueryException $exception) {
            Log::error($exception->getMessage());
            DB::rollBack();
            return false;

        }

    }


}